package com.jian.mall.produce.service.impl;

import com.jian.mall.common.content.SpuStatusEnum;
import com.jian.mall.common.to.elasticsearch.Attr;
import com.jian.mall.common.to.elasticsearch.SkuEsTo;
import com.jian.mall.common.to.ware.WareSkuInfoTo;
import com.jian.mall.common.utils.R;
import com.jian.mall.produce.dao.AttrGroupDao;
import com.jian.mall.produce.entity.*;
import com.jian.mall.produce.feign.SearchFeignService;
import com.jian.mall.produce.feign.WareFeignService;
import com.jian.mall.produce.service.*;
import com.jian.mall.produce.vo.SaleItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.produce.dao.SpuInfoDao;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), new QueryWrapper<SpuInfoEntity>());

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.like("spu_name", key).or().eq("id", key));
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !brandId.equals("0")) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")) {
            wrapper.eq("catalog_id", catelogId);
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);

    }

    @Override
    public void upProduce(Long spuId) {
        List<SkuEsTo> skuEsTos = new ArrayList<>();
        List<SkuInfoEntity> skuInfoEntities =
                skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        // attrs的值 初始化检索出来
        List<ProductAttrValueEntity> productAttrValueEntityList =
                productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> attrNeedIds = attrService.selectNeedSearchByAttrIds(attrIds);

        HashSet<Long> needAttrIdSet = new HashSet<>(attrNeedIds);

        List<Attr> attrs = productAttrValueEntityList.stream()
                .filter(f -> needAttrIdSet.contains(f.getAttrId())) // 过滤掉不需要搜索的
                .map(m -> {
                    Attr attr = new Attr();
                    attr.setAttrId(m.getAttrId());
                    attr.setAttrValue(m.getAttrValue());
                    attr.setAttrName(m.getAttrName());
                    return attr;
                }).collect(Collectors.toList());

        // 远程调用ware查询库存信息

        R r1 = wareFeignService.bySkuIds(skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList()));
        LinkedHashMap<Long, Integer> stockMap = new LinkedHashMap<>();
        if (r1.getCode() == 0) {
            List data = (List) r1.get("data");
            for (Object o : data) {
                Map m = (Map) o;
                Integer skuId = (Integer) m.get("skuId");
                Integer stock = (Integer) m.get("stock");
                stockMap.put(skuId.longValue(), stock == null ? 0 : stock);
            }
        }

        // 循环添加sku的信息
        skuInfoEntities.forEach(sku -> {
            SkuEsTo skuEsTo = new SkuEsTo();
            BeanUtils.copyProperties(sku, skuEsTo);
            skuEsTo.setSkuImg(sku.getSkuDefaultImg());
            skuEsTo.setSkuPrice(sku.getPrice());

            // attrs 的属性
            skuEsTo.setAttrs(attrs);

            // brand 信息
            BrandEntity brand = brandService.getById(skuEsTo.getBrandId());
            skuEsTo.setBrandImg(brand.getLogo());
            skuEsTo.setBrandName(brand.getName());

            // category 信息
            CategoryEntity category = categoryService.getById(skuEsTo.getCatalogId());
            skuEsTo.setCatalogName(category.getName());

            // 查看库存信息
            Integer stock = stockMap.get(sku.getSkuId());
            if (stock != null)
                skuEsTo.setHasStock(stock != 0);
            else
                skuEsTo.setHasStock(false);

            skuEsTo.setHotScore(0L);
            skuEsTos.add(skuEsTo);
        });

        R r = searchFeignService.saveProduct(skuEsTos);
        if (r.getCode() == 0) {
            // 商品上架成功 修改商品状态上架
            SpuInfoEntity entity = new SpuInfoEntity();
            entity.setId(spuId);
            entity.setPublishStatus(SpuStatusEnum.STATUS_UP.getCode());
            baseMapper.updateById(entity);
        }
    }

    @Override
    public SaleItemVo getSkuItemInfo(Long skuId) {
        SaleItemVo itemVo = new SaleItemVo();
        // sku基本信息
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        itemVo.setInfo(skuInfoEntity);
        // sku的图片信息
        List<SkuImagesEntity> imagesEntities = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
        itemVo.setImages(imagesEntities);
        // sku的销售组合
        List<SaleItemVo.SkuItemSaleAttr> saleAttrs =  skuInfoService.selectSaleAttrValue(spuId);
        itemVo.setSaleAttrs(saleAttrs);
        // spu的介绍
        SpuInfoDescEntity descEntity = spuInfoDescService.getById(spuId);
        itemVo.setDesp(descEntity);
        // spu的规格参数信息
        Long catalogId = skuInfoEntity.getCatalogId();
        List<SaleItemVo.SpuGroupAttr> spuGroupAttrs = attrGroupDao.selectSpuAttrsByGroup(spuId,catalogId);
        itemVo.setSpuItemBases(spuGroupAttrs);
        return itemVo;
    }

}